<template>
  <div class="app-container">
    <div class="page-header">
      <el-alert
        title="商户基本信息配置"
        description="此页面显示商户基本信息列表中的第一条数据，当前为只读模式，所有字段已锁定无法编辑。如需修改请联系管理员。"
        type="warning"
        :closable="false"
        show-icon>
      </el-alert>
    </div>
    
    <!-- 无数据提示 -->
    <div v-if="showNoDataTip" class="no-data-container">
      <div class="no-data-content">
        <i class="el-icon-warning" style="font-size: 48px; color: #E6A23C; margin-bottom: 16px;"></i>
        <h3 style="color: #606266; margin: 0 0 8px 0;">未查询到商户基本配置数据</h3>
        <p style="color: #909399; margin: 0;">请联系管理员进行配置</p>
      </div>
    </div>
    
    <!-- 表单区域 -->
    <el-form v-if="!showNoDataTip" ref="form" :model="form" :rules="rules" label-width="120px" v-loading="loading">
      <el-row>
        <el-col :span="12">
          <el-form-item label="AppID" prop="wechatAppid">
            <el-input v-model="form.wechatAppid" placeholder="请输入微信小程序AppID" :readonly="isReadOnly" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="小程序名称" prop="wechatName">
            <el-input v-model="form.wechatName" placeholder="请输入微信小程序名称" :readonly="isReadOnly" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="AppSecret" prop="wechatAppsecret">
            <el-input
              v-model="form.wechatAppsecret"
              placeholder="请输入微信小程序AppSecret"
              show-password
              :readonly="isReadOnly"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组织机构ID" prop="orgId">
            <el-input v-model="form.orgId" placeholder="请输入组织机构ID" :readonly="isReadOnly" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="微信商户号" prop="mchId">
            <el-input v-model="form.mchId" placeholder="请输入微信商户号" :readonly="isReadOnly" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付API密钥" prop="payApiclientKey">
            <el-upload
              class="upload-demo"
              :action="upload.url"
              :headers="upload.headers"
              :file-list="payKeyFileList"
              :on-success="handlePayKeySuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="handleExceed"
              accept=".pem,.p12,.key"
              :disabled="isReadOnly"
            >
              <el-button size="small" type="primary" :disabled="isReadOnly">选择文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传.pem/.p12/.key文件，且不超过10MB</div>
            </el-upload>
            <el-input v-if="form.payApiclientKey" v-model="form.payApiclientKey" readonly placeholder="文件上传后自动填入URL" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="API商户证书序列号" prop="apiMchKey">
            <el-input
              v-model="form.apiMchKey"
              placeholder="请输入API商户证书序列号"
              show-password
              :readonly="isReadOnly"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="APIv3密钥" prop="apiV3Key">
            <el-input
              v-model="form.apiV3Key"
              placeholder="请输入APIv3密钥"
              show-password
              :readonly="isReadOnly"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="小程序自动上传密钥" prop="uploadKeyUrl">
            <el-upload
              class="upload-demo"
              :action="upload.url"
              :headers="upload.headers"
              :file-list="uploadKeyFileList"
              :on-success="handleUploadKeySuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="handleExceed"
              accept=".pem,.p12,.key"
              :disabled="isReadOnly"
            >
              <el-button size="small" type="primary" :disabled="isReadOnly">选择文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传.pem/.p12/.key文件，且不超过10MB</div>
            </el-upload>
            <el-input v-if="form.uploadKeyUrl" v-model="form.uploadKeyUrl" readonly placeholder="文件上传后自动填入URL" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status" :disabled="isReadOnly">
              <el-radio
                v-for="dict in dict.type.sys_common_status"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核状态" prop="auditStatus">
            <el-radio-group v-model="form.auditStatus" :disabled="isReadOnly">
              <el-radio
                v-for="dict in dict.type.ec_audit_status"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    
    <!-- 表单底部按钮 -->
    <div v-if="!showNoDataTip && !isReadOnly" class="form-footer">
      <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
      <el-button type="info" @click="refreshData" :loading="loading">刷 新</el-button>
    </div>
  </div>
</template>

<script>
import { getVersion, addVersion, updateVersion, listVersion } from "@/api/fun/version"
import { getToken } from "@/utils/auth"
import store from "@/store"
import { checkPermi } from "@/utils/permission"

export default {
  name: "VersionForm",
  dicts: ['sys_common_status', 'ec_audit_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 是否显示无数据提示
      showNoDataTip: false,
      // 是否为只读模式（锁定所有字段）
      isReadOnly: true,
      // 表单参数
      form: {},
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      // 支付API密钥文件列表
      payKeyFileList: [],
      // 小程序自动上传密钥文件列表
      uploadKeyFileList: [],
      // 表单校验
      rules: {
        wechatAppid: [
          { required: true, message: "微信小程序AppID不能为空", trigger: "blur" }
        ],
        wechatName: [
          { required: true, message: "微信小程序名称不能为空", trigger: "blur" }
        ],
        wechatAppsecret: [
          { required: true, message: "微信小程序AppSecret不能为空", trigger: "blur" }
        ],
        orgId: [
          { required: true, message: "组织机构ID不能为空", trigger: "blur" }
        ],
        mchId: [
          { required: true, message: "微信商户号不能为空", trigger: "blur" }
        ],
        payApiclientKey: [
          { required: true, message: "支付API密钥不能为空", trigger: "blur" }
        ],
        apiMchKey: [
          { required: true, message: "API商户密钥不能为空", trigger: "blur" }
        ],
        apiV3Key: [
          { required: true, message: "APIv3密钥不能为空", trigger: "blur" }
        ],
        uploadKeyUrl: [
          { required: true, message: "密钥上传URL不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    const pageType = this.$route.query.pageType
    const id = this.$route.query.id
    const currentPath = this.$route.path

    // 检测pageType=add时的权限
    if (pageType === 'add') {
      // 检查新增权限 fun:version:add
      if (!this.checkPermi(['fun:version:add'])) {
        this.$modal.msgError('没有权限访问此页面')
        this.$tab.closePage()
        return
      }
      // 有权限则重置表单准备新增
      this.reset()
      this.loading = false
      return
    }

    if (pageType === 'edit' && id) {
      this.form.id = id
      this.getInfo(id)
    } else if (currentPath === '/version/version/config' && !pageType) {
      // 从config路径访问且没有pageType时，获取当前用户组织的数据
      this.getCurrentUserVersionDataWithError()
    } else if (!pageType) {
      // 没有传pageType时，根据orgId进行过滤
      this.getVersionDataByOrgId()
    } else {
      // 页面加载时获取第一条商户基本信息数据
      this.getFirstVersionData()
    }
  },
  mounted() {
    // 监听刷新事件
    this.$eventBus.$on('refreshVersionList', () => {
      // 表单页面不需要处理刷新事件
    })
  },
  beforeDestroy() {
    // 移除事件监听器
    this.$eventBus.$off('refreshVersionList')
  },
  methods: {
    /** 权限检查方法 */
    checkPermi(permissions) {
      return checkPermi(permissions)
    },
    /** 获取第一条商户基本信息数据 */
    getFirstVersionData() {
      this.loading = true
      listVersion({}).then(response => {
        if (response.rows && response.rows.length > 0) {
          // 获取第一条数据
          this.form = response.rows[0]
        } else {
          // 如果没有数据，重置表单
          this.reset()
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.reset()
      })
    },
    /** 获取当前用户组织的版本数据 */
    getCurrentUserVersionData() {
      this.loading = true
      const currentDeptId = store.getters.deptId
      const params = {
        orgId: currentDeptId
      }
      listVersion(params).then(response => {
        if (response.rows && response.rows.length > 0) {
          // 获取第一条当前用户组织的数据
          this.form = response.rows[0]
        } else {
          // 如果没有数据，重置表单
          this.reset()
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.reset()
      })
    },
    /** 获取当前用户组织的版本数据（带错误提示） */
    getCurrentUserVersionDataWithError() {
      this.loading = true
      this.showNoDataTip = false
      const currentDeptId = store.getters.deptId
      const params = {
        orgId: currentDeptId
      }
      listVersion(params).then(response => {
        if (response.rows && response.rows.length > 0) {
          // 获取第一条当前用户组织的数据
          this.form = response.rows[0]
          this.showNoDataTip = false
        } else {
          // 如果没有数据，显示页面提示信息
          this.showNoDataTip = true
          this.reset()
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.showNoDataTip = true
        this.reset()
      })
    },
    /** 根据orgId过滤获取版本数据 */
    getVersionDataByOrgId() {
      this.loading = true
      this.showNoDataTip = false
      const currentDeptId = store.getters.deptId
      const params = {
        orgId: currentDeptId
      }
      listVersion(params).then(response => {
        if (response.rows && response.rows.length > 0) {
          // 获取第一条匹配的数据
          this.form = response.rows[0]
          this.showNoDataTip = false
        } else {
          // 如果没有数据，显示页面提示信息
          this.showNoDataTip = true
          this.reset()
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.showNoDataTip = true
        this.reset()
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        wechatAppid: null,
        wechatName: null,
        wechatAppsecret: null,
        orgId: null,
        mchId: null,
        payApiclientKey: null,
        apiMchKey: null,
        apiV3Key: null,
        uploadKeyUrl: null,
        status: null,
        auditStatus: null,
        isDefault: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      }
      this.resetForm("form")
    },
    /** 获取详情 */
    getInfo(id) {
      this.loading = true
      getVersion(id).then(response => {
        this.form = response.data
        this.loading = false
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          if (this.form.id != null) {
            updateVersion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.loading = false
              // 修改成功后重新获取数据
              const currentPath = this.$route.path
              if (currentPath === '/version/version/config') {
                this.getCurrentUserVersionData()
              } else {
                this.getFirstVersionData()
              }
              this.$eventBus.$emit('refreshVersionList')
            }).catch(() => {
              this.loading = false
            })
          } else {
            // 新增时设置createBy为当前登录用户ID，orgId为当前用户部门ID
            const currentUserId = store.getters.userId
            const currentDeptId = store.getters.deptId
            this.form.createBy = currentUserId
            this.form.orgId = currentDeptId
            addVersion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.loading = false
              // 新增成功后重新获取数据
              const currentPath = this.$route.path
              if (currentPath === '/version/version/config') {
                this.getCurrentUserVersionData()
              } else {
                this.getFirstVersionData()
              }
              this.$eventBus.$emit('refreshVersionList')
            }).catch(() => {
              this.loading = false
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.$tab.closePage()
    },
    /** 刷新数据 */
    refreshData() {
      const currentPath = this.$route.path
      if (currentPath === '/version/version/config') {
        this.getCurrentUserVersionData()
      } else {
        this.getFirstVersionData()
      }
    },
    /** 文件上传前的钩子 */
    beforeUpload(file) {
      const isValidType = ['application/x-pkcs12', 'application/x-pem-file', 'application/octet-stream'].includes(file.type) ||
                         file.name.endsWith('.pem') || file.name.endsWith('.p12') || file.name.endsWith('.key')
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isValidType) {
        this.$modal.msgError('上传文件只能是 .pem/.p12/.key 格式!')
        return false
      }
      if (!isLt10M) {
        this.$modal.msgError('上传文件大小不能超过 10MB!')
        return false
      }
      this.upload.isUploading = true
      return true
    },
    /** 支付API密钥文件上传成功处理 */
    handlePayKeySuccess(response, file) {
      this.upload.isUploading = false
      if (response.code === 200) {
        this.form.payApiclientKey = response.url
        this.payKeyFileList = [{ name: file.name, url: response.url }]
        this.$modal.msgSuccess('支付API密钥文件上传成功')
      } else {
        this.$modal.msgError(response.msg || '上传失败')
      }
    },
    /** 小程序自动上传密钥文件上传成功处理 */
    handleUploadKeySuccess(response, file) {
      this.upload.isUploading = false
      if (response.code === 200) {
        this.form.uploadKeyUrl = response.url
        this.uploadKeyFileList = [{ name: file.name, url: response.url }]
        this.$modal.msgSuccess('小程序自动上传密钥文件上传成功')
      } else {
        this.$modal.msgError(response.msg || '上传失败')
      }
    },
    /** 文件上传失败处理 */
    handleUploadError() {
      this.upload.isUploading = false
      this.$modal.msgError('上传失败，请重试')
    },
    /** 文件超出个数限制时的钩子 */
    handleExceed() {
      this.$modal.msgError('最多只能上传1个文件')
    }
  }
}
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
}

.el-form {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.upload-demo {
  margin-bottom: 10px;
}

.upload-demo .el-upload__tip {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input[readonly] {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

.no-data-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.no-data-content {
  text-align: center;
  padding: 40px;
}
</style>
